const querystring = require('querystring')
const handleUserRouter = require('./src/router/user')
const handleBlogRouter = require('./src/router/blog')
const handleCommentRouter = require('./src/router/comment')
const handleNavRouter = require('./src/router/nav')
const handleSiteRouter = require('./src/router/site')

// 处理postData
const getPostData = req => {
  return new Promise((resolve, reject) => {
    if (req.method !== 'POST') {
      resolve({})
      return
    }
    if (req.headers['content-type'] !== 'application/json') {
      resolve({})
      return
    }
    let postData = ''
    req.on('data', chunk => {
      postData += chunk.toString()
    })

    req.on('end', () => {
      if (!postData) {
        resolve({})
        return
      }
      resolve(JSON.parse(postData))
    })
  })
}

const serverHandle = (req, res) => {
  // 设置返回格式
  res.setHeader('Content-type', 'application/json')

  req.path = req.url.split('?')[0]

  req.query = querystring.parse(req.url.split('?')[1])

  getPostData(req).then(data => {
    req.body = data
    // 用户
    const userData = handleUserRouter(req, res)
    if (userData) {
      userData.then(result => {
        res.end(JSON.stringify(result))
      })
      return
    }

    // 文章
    const blogResult = handleBlogRouter(req, res)
    if (blogResult) {
      blogResult.then(result => {
        res.end(JSON.stringify(result))
      })
      return
    }

    // 评论
    const commentResult = handleCommentRouter(req, res)
    if (commentResult) {
      commentResult.then(result => {
        res.end(JSON.stringify(result))
      })
      return
    }

    // 导航
    const navResult = handleNavRouter(req, res)
    if (navResult) {
      navResult.then(result => {
        res.end(JSON.stringify(result))
      })
      return
    }

    // 站点
    const siteResult = handleSiteRouter(req, res)
    if (siteResult) {
      siteResult.then(result => {
        res.end(JSON.stringify(result))
      })
      return
    }

    res.writeHead(404, { 'Content-type': 'text/plain' })
    res.write('404 Not Found \n')
    res.end()
  })
}

module.exports = serverHandle
